<template>
  <PageContainer title="数据概览">
    <!-- 图表展示区域 -->
    <div class="charts-grid">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>投放趋势图</span>
            <el-radio-group v-model="disposalPeriod" size="small">
              <el-radio-button value="7d">近7天</el-radio-button>
              <el-radio-button value="30d">近30天</el-radio-button>
              <el-radio-button value="90d">近90天</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="disposalChartRef" class="chart-container"></div>
      </el-card>

      <el-card class="chart-card">
        <template #header>
          <span>设备状态分布</span>
        </template>
        <div ref="deviceStatusChartRef" class="chart-container"></div>
      </el-card>

      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>收益趋势图</span>
            <el-radio-group v-model="revenuePeriod" size="small">
              <el-radio-button value="7d">近7天</el-radio-button>
              <el-radio-button value="30d">近30天</el-radio-button>
              <el-radio-button value="90d">近90天</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="revenueChartRef" class="chart-container"></div>
      </el-card>

      <el-card class="chart-card">
        <template #header>
          <span>用户活跃度</span>
        </template>
        <div ref="userActivityChartRef" class="chart-container"></div>
      </el-card>
    </div>

    <!-- 快捷操作区域 -->
    <div class="quick-actions">
      <el-card class="action-card" @click="router.push('/disposal/exceptions')">
        <div class="action-content">
          <el-icon :size="32" color="#E6A23C">
            <Warning />
          </el-icon>
          <div class="action-info">
            <div class="action-title">待处理任务</div>
            <div class="action-count">{{ dashboardData.pendingTasks }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="action-card" @click="router.push('/device/monitor')">
        <div class="action-content">
          <el-icon :size="32" color="#F56C6C">
            <Monitor />
          </el-icon>
          <div class="action-info">
            <div class="action-title">异常设备</div>
            <div class="action-count">{{ dashboardData.errorDevices }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="action-card" @click="router.push('/finance/withdrawal')">
        <div class="action-content">
          <el-icon :size="32" color="#409EFF">
            <Money />
          </el-icon>
          <div class="action-info">
            <div class="action-title">待审核提现</div>
            <div class="action-count">{{ dashboardData.pendingWithdrawals }}</div>
          </div>
        </div>
      </el-card>
    </div>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { Monitor, Money, Warning } from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import { getDashboardStats, getDisposalTrend, getRevenueTrend } from '@/api/dashboard'

const router = useRouter()

// 图表引用
const disposalChartRef = ref<HTMLElement>()
const deviceStatusChartRef = ref<HTMLElement>()
const revenueChartRef = ref<HTMLElement>()
const userActivityChartRef = ref<HTMLElement>()

// 图表实例
let disposalChart: echarts.ECharts
let deviceStatusChart: echarts.ECharts
let revenueChart: echarts.ECharts
let userActivityChart: echarts.ECharts

// 时间周期选择
const disposalPeriod = ref('7d')
const revenuePeriod = ref('7d')

// 仪表盘数据
const dashboardData = reactive({
  totalUsers: 12580,
  userTrend: '+12.5%',
  totalDevices: 156,
  deviceTrend: '+3.2%',
  todayDisposals: 2340,
  disposalTrend: '+8.7%',
  totalRevenue: '156,789.50',
  revenueTrend: '+15.3%',
  pendingTasks: 23,
  errorDevices: 5,
  pendingWithdrawals: 18
})

// 初始化投放趋势图
const initDisposalChart = () => {
  if (!disposalChartRef.value) return
  
  disposalChart = echarts.init(disposalChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['投放次数', '投放重量']
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: [
      {
        type: 'value',
        name: '投放次数',
        position: 'left'
      },
      {
        type: 'value',
        name: '投放重量(kg)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '投放次数',
        type: 'bar',
        data: [320, 332, 301, 334, 390, 330, 320],
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '投放重量',
        type: 'line',
        yAxisIndex: 1,
        data: [150, 232, 201, 154, 190, 330, 410],
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  
  disposalChart.setOption(option)
}

// 初始化设备状态分布图
const initDeviceStatusChart = () => {
  if (!deviceStatusChartRef.value) return
  
  deviceStatusChart = echarts.init(deviceStatusChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '设备状态',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 120, name: '在线', itemStyle: { color: '#67C23A' } },
          { value: 20, name: '离线', itemStyle: { color: '#909399' } },
          { value: 10, name: '已满', itemStyle: { color: '#E6A23C' } },
          { value: 6, name: '故障', itemStyle: { color: '#F56C6C' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  deviceStatusChart.setOption(option)
}

// 初始化收益趋势图
const initRevenueChart = () => {
  if (!revenueChartRef.value) return
  
  revenueChart = echarts.init(revenueChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '收益: ¥{c}'
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value',
      name: '收益(元)'
    },
    series: [
      {
        name: '收益',
        type: 'line',
        data: [1200, 1320, 1010, 1340, 1900, 2330, 2100],
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        }
      }
    ]
  }
  
  revenueChart.setOption(option)
}

// 初始化用户活跃度图
const initUserActivityChart = () => {
  if (!userActivityChartRef.value) return
  
  userActivityChart = echarts.init(userActivityChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['新增用户', '活跃用户']
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增用户',
        type: 'bar',
        data: [20, 25, 18, 30, 35, 28, 22],
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '活跃用户',
        type: 'bar',
        data: [150, 180, 160, 200, 220, 190, 170],
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  userActivityChart.setOption(option)
}

// 加载数据
const loadDashboardData = async () => {
  try {
    const stats = await getDashboardStats()
    Object.assign(dashboardData, stats)
  } catch (error) {
    console.error('Failed to load dashboard data:', error)
  }
}

// 监听时间周期变化
watch(disposalPeriod, () => {
  // 重新加载投放趋势数据
  // loadDisposalTrend()
})

watch(revenuePeriod, () => {
  // 重新加载收益趋势数据
  // loadRevenueTrend()
})

// 窗口大小变化时重新调整图表
const handleResize = () => {
  disposalChart?.resize()
  deviceStatusChart?.resize()
  revenueChart?.resize()
  userActivityChart?.resize()
}

onMounted(async () => {
  await loadDashboardData()
  
  await nextTick()
  
  initDisposalChart()
  initDeviceStatusChart()
  initRevenueChart()
  initUserActivityChart()
  
  window.addEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.charts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;

  .chart-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 300px;
    }
  }
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;

  .action-card {
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .action-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .action-info {
        .action-title {
          font-size: 14px;
          color: #606266;
          margin-bottom: 4px;
        }

        .action-count {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
        }
      }
    }
  }
}

@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .quick-actions {
    grid-template-columns: 1fr;
  }
}
</style>